<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import gameService from '../services/gameService'
import type { Soup, GameRecord } from '../types'

const router = useRouter()
const popularSoups = ref<Soup[]>([])
const recentGames = ref<GameRecord[]>([])
const loading = ref(false)
const error = ref('')
const searchQuery = ref('')
const categoryFilter = ref('all')

// 计算过滤后的海龟汤列表
const filteredSoups = computed(() => {
  let result = popularSoups.value
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(soup => 
      soup.title.toLowerCase().includes(query) ||
      soup.description.toLowerCase().includes(query)
    )
  }
  
  // 分类过滤
  if (categoryFilter.value !== 'all') {
    result = result.filter(soup => soup.category === categoryFilter.value)
  }
  
  return result
})

// 获取热门海龟汤
const fetchPopularSoups = async () => {
  loading.value = true
  error.value = ''
  
  try {
    // 由于是模拟环境，我们直接使用 mock 数据
    popularSoups.value = [
      {
        id: '1',
        title: '神秘的敲门声',
        description: '一个寒冷的夜晚，突然传来一阵急促的敲门声...',
        difficulty: 'easy',
        category: 'mystery',
        playerCount: 128,
        completionRate: 78
      },
      {
        id: '2', 
        title: '消失的钥匙',
        description: '明明记得放在桌上的钥匙，却怎么也找不到了...',
        difficulty: 'medium',
        category: 'mystery',
        playerCount: 96,
        completionRate: 65
      },
      {
        id: '3',
        title: '深夜来电',
        description: '凌晨3点，手机突然响起，显示的是一个未知号码...',
        difficulty: 'hard',
        category: 'horror',
        playerCount: 82,
        completionRate: 45
      },
      {
        id: '4',
        title: '古老的照片',
        description: '奶奶的旧相册里，有一张从未见过的神秘照片...',
        difficulty: 'medium',
        category: 'fantasy',
        playerCount: 75,
        completionRate: 60
      }
    ]
  } catch (err: any) {
    error.value = err.message || '获取海龟汤列表失败'
  } finally {
    loading.value = false
  }
}

// 获取最近游戏记录
const fetchRecentGames = async () => {
  try {
    // 模拟数据
    recentGames.value = [
      {
        id: 'g1',
        soupId: '1',
        soupTitle: '神秘的敲门声',
        startTime: new Date(Date.now() - 3600000).toISOString(),
        endTime: new Date(Date.now() - 1800000).toISOString(),
        status: 'completed',
        userId: 'u1',
        userName: '推理大师',
        turns: 15
      },
      {
        id: 'g2',
        soupId: '2', 
        soupTitle: '消失的钥匙',
        startTime: new Date(Date.now() - 7200000).toISOString(),
        status: 'in_progress',
        userId: 'u2',
        userName: '解谜达人',
        turns: 8
      }
    ]
  } catch (err) {
    console.error('获取最近游戏记录失败', err)
  }
}

// 开始游戏
const startGame = (soupId: string) => {
  router.push(`/game/${soupId}`)
}

// 进入聊天室
const joinChat = (gameId: string) => {
  router.push(`/chat/${gameId}`)
}

// 创建房间
const createRoom = () => {
  router.push('/create-room')
}

// 创建海龟汤
const createSoup = () => {
  router.push('/create-soup')
}

// 格式化时间
const formatTime = (timeString: string) => {
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN', { 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取难度文本
const getDifficultyText = (difficulty: string) => {
  const map: Record<string, string> = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return map[difficulty] || difficulty
}

// 获取难度类名
const getDifficultyClass = (difficulty: string) => {
  return `difficulty-${difficulty}`
}

// 获取分类文本
const getCategoryText = (category: string) => {
  const map: Record<string, string> = {
    mystery: '悬疑',
    horror: '恐怖',
    fantasy: '奇幻',
    sciFi: '科幻',
    daily: '日常'
  }
  return map[category] || category
}

// 组件挂载时获取数据
onMounted(() => {
  fetchPopularSoups()
  fetchRecentGames()
})
</script>

<template>
  <div class="home-page">
    <!-- 英雄区 -->
    <section class="hero-section">
      <div class="hero-content">
        <h1>海龟汤AI聊天室</h1>
        <p>用推理解锁谜题，与AI展开精彩的问答对决</p>
        <div class="hero-actions">
          <button class="btn-primary" @click="createRoom">
            创建房间
          </button>
          <button class="btn-secondary" @click="createSoup">
            创建海龟汤
          </button>
        </div>
      </div>
    </section>

    <!-- 搜索和过滤区 -->
    <section class="search-section">
      <div class="search-container">
        <div class="search-input-wrapper">
          <input
            type="text"
            v-model="searchQuery"
            placeholder="搜索海龟汤题目..."
            class="search-input"
          />
          <i class="search-icon">🔍</i>
        </div>
        <div class="category-filters">
          <button
            v-for="category in ['all', 'mystery', 'horror', 'fantasy', 'sciFi', 'daily']"
            :key="category"
            class="category-btn"
            :class="{ active: categoryFilter === category }"
            @click="categoryFilter = category"
          >
            {{ category === 'all' ? '全部' : getCategoryText(category) }}
          </button>
        </div>
      </div>
    </section>

    <!-- 主要内容区 -->
    <section class="main-content">
      <!-- 海龟汤列表 -->
      <div class="content-column">
        <div class="section-header">
          <h2>热门海龟汤</h2>
        </div>

        <div v-if="loading" class="loading-container">
          <p>加载中...</p>
        </div>

        <div v-else-if="error" class="error-container">
          <p>{{ error }}</p>
        </div>

        <div v-else-if="filteredSoups.length === 0" class="empty-container">
          <p>没有找到匹配的海龟汤</p>
        </div>

        <div v-else class="soups-grid">
          <div
            v-for="soup in filteredSoups"
            :key="soup.id"
            class="soup-card"
          >
            <div class="soup-card-header">
              <h3>{{ soup.title }}</h3>
              <span :class="['difficulty-badge', getDifficultyClass(soup.difficulty)]">
                {{ getDifficultyText(soup.difficulty) }}
              </span>
            </div>
            
            <p class="soup-description">{{ soup.description }}</p>
            
            <div class="soup-category">
              <span class="category-label">
                {{ getCategoryText(soup.category) }}
              </span>
            </div>
            
            <div class="soup-stats">
              <span class="stat-item">
                <i>👥</i> {{ soup.playerCount }}人参与
              </span>
              <span class="stat-item">
                <i>✅</i> {{ soup.completionRate }}%完成率
              </span>
            </div>
            
            <button class="btn-card" @click="startGame(soup.id)">
              开始游戏
            </button>
          </div>
        </div>
      </div>

      <!-- 侧边栏 -->
      <div class="sidebar-column">
        <!-- 最近游戏 -->
        <div class="sidebar-section">
          <h3>最近游戏</h3>
          <div class="recent-games">
            <div
              v-for="game in recentGames"
              :key="game.id"
              class="game-item"
              :class="{ 'in-progress': game.status === 'in_progress' }"
            >
              <div class="game-info">
                <h4>{{ game.soupTitle }}</h4>
                <p class="game-player">{{ game.userName }}</p>
                <p class="game-time">
                  {{ formatTime(game.startTime) }}
                  <span v-if="game.status === 'completed'"> - {{ formatTime(game.endTime) }}</span>
                </p>
                <div class="game-stats">
                  <span>{{ game.turns }}回合</span>
                  <span :class="['game-status', game.status]">
                    {{ game.status === 'completed' ? '已完成' : '进行中' }}
                  </span>
                </div>
              </div>
              <button class="btn-chat" @click="joinChat(game.id)">
                进入聊天
              </button>
            </div>
          </div>
        </div>

        <!-- 游戏规则 -->
        <div class="sidebar-section">
          <h3>游戏规则</h3>
          <div class="game-rules">
            <ol>
              <li>玩家通过提问来推测海龟汤的真相</li>
              <li>AI只能回答"是"、"否"或"无关"</li>
              <li>在限定的回合内尽可能接近真相</li>
              <li>可以邀请好友一起参与讨论</li>
            </ol>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<style scoped>
.home-page {
  min-height: calc(100vh - 120px);
  background-color: #f5f7fa;
}

/* 英雄区 */
.hero-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 60px 0;
  text-align: center;
}

.hero-content h1 {
  font-size: 42px;
  margin-bottom: 16px;
  font-weight: 700;
}

.hero-content p {
  font-size: 18px;
  margin-bottom: 32px;
  opacity: 0.9;
}

.hero-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
}

/* 搜索区 */
.search-section {
  background-color: white;
  padding: 20px 0;
  margin-bottom: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.search-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-input-wrapper {
  position: relative;
}

.search-input {
  width: 100%;
  padding: 12px 40px 12px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.search-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.search-icon {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  font-size: 18px;
}

.category-filters {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.category-btn {
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  background-color: white;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.category-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.category-btn.active {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

/* 主要内容区 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: grid;
  grid-template-columns: 1fr 340px;
  gap: 30px;
}

/* 海龟汤列表 */
.content-column {
  min-width: 0;
}

.section-header {
  margin-bottom: 24px;
}

.section-header h2 {
  font-size: 24px;
  color: #262626;
  font-weight: 600;
}

.soups-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.soup-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
}

.soup-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.soup-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.soup-card-header h3 {
  font-size: 18px;
  color: #262626;
  margin: 0;
  flex: 1;
}

.difficulty-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  margin-left: 8px;
}

.difficulty-easy {
  background-color: #f6ffed;
  color: #52c41a;
}

.difficulty-medium {
  background-color: #fffbe6;
  color: #faad14;
}

.difficulty-hard {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.soup-description {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 16px;
  flex: 1;
}

.soup-category {
  margin-bottom: 12px;
}

.category-label {
  display: inline-block;
  padding: 4px 12px;
  background-color: #f0f2f5;
  color: #666;
  border-radius: 4px;
  font-size: 12px;
}

.soup-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  font-size: 14px;
  color: #999;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 侧边栏 */
.sidebar-column {
  min-width: 0;
}

.sidebar-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.sidebar-section h3 {
  font-size: 18px;
  color: #262626;
  margin-bottom: 16px;
  font-weight: 600;
}

/* 最近游戏 */
.recent-games {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.game-item {
  display: flex;
  flex-direction: column;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  background-color: #fafafa;
}

.game-item.in-progress {
  background-color: #e6f7ff;
  border-color: #91d5ff;
}

.game-info h4 {
  font-size: 16px;
  color: #262626;
  margin: 0 0 8px 0;
}

.game-player {
  font-size: 14px;
  color: #1890ff;
  margin: 0 0 4px 0;
}

.game-time {
  font-size: 12px;
  color: #999;
  margin: 0 0 8px 0;
}

.game-stats {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  margin-bottom: 12px;
}

.game-status {
  padding: 2px 6px;
  border-radius: 3px;
  font-weight: 500;
}

.game-status.completed {
  background-color: #f6ffed;
  color: #52c41a;
}

.game-status.in_progress {
  background-color: #e6f7ff;
  color: #1890ff;
}

/* 游戏规则 */
.game-rules ol {
  padding-left: 20px;
  margin: 0;
}

.game-rules li {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 8px;
}

/* 按钮样式 */
.btn-card,
.btn-chat {
  width: 100%;
  padding: 10px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-card:hover,
.btn-chat:hover {
  background-color: #40a9ff;
}

.btn-secondary {
  padding: 12px 24px;
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid white;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-secondary:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

/* 加载和错误状态 */
.loading-container,
.error-container,
.empty-container {
  text-align: center;
  padding: 60px 0;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .main-content {
    grid-template-columns: 1fr;
  }
  
  .sidebar-column {
    order: -1;
  }
}

@media (max-width: 768px) {
  .hero-content h1 {
    font-size: 32px;
  }
  
  .hero-content p {
    font-size: 16px;
  }
  
  .hero-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .hero-actions button {
    width: 200px;
  }
  
  .soups-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .hero-section {
    padding: 40px 0;
  }
  
  .hero-content h1 {
    font-size: 24px;
  }
  
  .category-filters {
    justify-content: center;
  }
  
  .main-content {
    padding: 0 16px;
  }
}
</style>